package cn.sunxiansheng.elk.listener;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * Description: 配置文件已加载，Environment 对象已初始化
 * 使用 ApplicationEnvironmentPreparedEvent 读取 application.yml 文件中的 sun-rays.elk.logstash.host 和 sun-rays.elk.logstash.port 配置
 *
 * @Author sun
 * @Create 2025/1/10 22:46
 * @Version 1.0
 */
public class ELKEnvironmentPreparedListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();

        // 获取 socket.host 属性并提供默认值
        String socketHost = environment.getProperty("sun-rays.elk.logstash.host", "127.0.0.1");
        if ("127.0.0.1".equals(socketHost)) {
            System.err.println("WARNING: sun-rays.elk.logstash.host 属性未设置，使用默认值: " + socketHost);
        }

        // 获取 socket.port 属性并提供默认值
        String socketPort = environment.getProperty("sun-rays.elk.logstash.port", "8080");
        if ("8080".equals(socketPort)) {
            System.err.println("WARNING: sun-rays.elk.logstash.port 属性未设置，使用默认值: " + socketPort);
        }

        // 获取 log.module 属性并提供默认值
        String logModule = environment.getProperty("sun-rays.elk.module", "defaultModule");
        if ("defaultModule".equals(logModule)) {
            System.err.println("WARNING: sun-rays.log4j2.module 属性未设置，使用默认值: " + logModule);
        }

        // 将属性设置为系统属性
        System.setProperty("socket.host", socketHost);
        System.setProperty("socket.port", socketPort);
        System.setProperty("log.module", logModule);
    }

    /**
     * 当前监听器的启动顺序需要在日志配置监听器的前面，保证在日志文件初始化之前读取 application.yml 的配置。
     *
     * @return
     */
    @Override
    public int getOrder() {
        return LoggingApplicationListener.DEFAULT_ORDER - 1;
    }
}
